//
//  CXHelper.swift
//  CXRobotServer
//
//  Created by ezreal on 2019/4/24.
//

import Foundation
import SwifterSwift

class CXHelper: NSObject {

    class func getSystemDate() -> String {
        let dformatter = DateFormatter()
        dformatter.dateFormat = "YYYY/MM/dd#HH:mm:ss"
        return dformatter.string(from: Date())
    }
    
    class func stitchingStringFromDictionary(dict:Dictionary<String,String>) ->String?{
        
        var components = URLComponents(string: "")
        var queryItems:Array<URLQueryItem> = Array()
        
        for (key,value) in dict {
            let queryItem = URLQueryItem(name: key, value: value)
            queryItems.append(queryItem)
        }
        components?.queryItems = queryItems
        return components?.query
    }
    
    class func getParamData(param:Dictionary<String,String>?) -> Data? {
        
        var parameters = Dictionary<String, String>()
        parameters["json"] = "ok"
        
        if (param != nil) {
            let desString = self.stitchingStringFromDictionary(dict: param!)
            parameters["parameter"] = desString?.urlEncoded
        }
        
        var components = URLComponents(string: "")
        
        var queryItems:Array<URLQueryItem> = Array()
        
        for (key,value) in parameters {
            let queryItem = URLQueryItem(name: key, value: value)
            queryItems.append(queryItem)
        }
        
        components?.queryItems = queryItems;
        
        let encodeQuery = components?.percentEncodedQuery!
        
        if (encodeQuery != nil) {
            return encodeQuery!.data(using: String.Encoding.utf8)
        }else{
            return nil
        }
    }
    
    class func getParamString(param:Dictionary<String,String>?) -> String {
        
        var parameters = Dictionary<String, String>()
        parameters["json"] = "ok"
        
        if (param != nil) {
            let desString = self.stitchingStringFromDictionary(dict: param!)
            parameters["parameter"] = desString?.urlEncoded
        }
        
        var components = URLComponents(string: "")
        
        var queryItems:Array<URLQueryItem> = Array()
        
        for (key,value) in parameters {
            let queryItem = URLQueryItem(name: key, value: value)
            queryItems.append(queryItem)
        }
        
        components?.queryItems = queryItems;
        
        let encodeQuery = components?.percentEncodedQuery!
        
        if (encodeQuery != nil) {
            return encodeQuery!
        }else{
            return ""
        }
    }
    
    class func codeEncrypt(code:Int64,key:Int64) -> Int64 {
        return code + key * 2 - 123456;
    }
}
